﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;

namespace Yule8xWechat
{
    public partial class DbView : System.Web.UI.Page
    {
        protected DataTable dtTables, dtList;
        protected string table, con, sql, action;

        Dictionary<string, string> loginusers = new Dictionary<string, string>();

        protected int limit, count = -1;
        protected DataTable QueryTable(string table, int limit = 5)
        {
            sql = "select top " + limit + " * from " + table;
            return DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable(sql);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // 允许登录的用户名
            loginusers.Add("testadmin", "1314159");

            // 请求动作字符串
            action = RequestUtil.ParamsString("action", maxLen: 32);

            // 登录操作
            if ("dologin" == action)
            {
                this.dologin();
                Response.End();
            }

            // 检查登录
            if (action != "login")
            {
                object sess = Session["debuglogin"];
                if (null == sess || !loginusers.ContainsKey(sess.ToString()))
                {
                    Response.Redirect("DbView.aspx?action=login", true);
                }
            }

            table = RequestUtil.GetString("table", maxLen: 32);
            con = RequestUtil.ParamsString("con", maxLen: 32);
            // 清空指定的数据表
            if ("clear" == action && !string.IsNullOrEmpty(table))
            {
                sql = string.Format("truncate table {0};", table);
                count = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteNonQuery(sql);
                Response.Redirect(string.Format("DbView.aspx?r=clear-{0}-success", table), true);
            }

            // 查询数据库中所有数据表的名称
            dtTables = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable("SELECT Name FROM SysObjects Where XType='U' ORDER BY Name desc");

            // 清空数据库中所有数据表的数据
            if ("clearall" == action && dtTables.Rows.Count > 0)
            {
                string[] skillclear = new string[] { "t_game_currency", "t_game_manufacturer" };
                foreach (DataRow r in dtTables.Rows)
                {
                    table = r["Name"].ToString();
                    if (table.IndexOf("t_") == 0 && !skillclear.Contains(table))
                    {
                        sql = string.Format("truncate table {0};", table);
                        count = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteNonQuery(sql);
                    }
                }
                Response.Redirect("DbView.aspx?r=clear-alltables-success", true);
            }

            sql = RequestUtil.FormString("sql", isHtmlEncode:false, maxLen: 300);
            limit = RequestUtil.GetInteger("limit");
            string simple = RequestUtil.GetString("simple", maxLen: 16);
            if (limit < 1)
            {
                limit = 50;
            }
            if (!string.IsNullOrEmpty(table) && sql.Length < 1)
            {
                switch (con)
                {
                    case "bozhong":
                        sql = "select top 50 u.USERID, u.unionid, p.RoomCard from TUserProperty p LEFT JOIN TUSERS u ON p.USERID=U.USERID order by u.USERID desc;";
                        break;
                    case "wanghu":
                        sql = string.Format("select top {0} c.UserID, c.Currency, i.GameID, i.Accounts, i.NickName, i.UserUin FROM RYTreasureDB.dbo.UserCurrencyInfo c LEFT JOIN RYAccountsDB.dbo.AccountsInfo i ON c.UserID=i.UserID order by c.USERID DESC", limit);
                        break;
                    default:
                        if ("yes" == simple)
                        {
                            Dictionary<string, string> simpleQuery = GetSimpleQuerySqlstement();
                            if (simpleQuery.ContainsKey(table))
                            {
                                sql = string.Format(simpleQuery[table], limit);
                            }
                        }
                        if (string.IsNullOrEmpty(sql))
                        {
                            sql = "select top " + limit + " * from " + table;
                        }
                        break;
                }
            }

            if (!string.IsNullOrWhiteSpace(sql))
            {
                string operate = sql.Substring(0, sql.IndexOf(' ')).ToLower();
                switch (operate)
                {
                    case "insert":
                    case "update":
                    case "delete":
                    case "truncate":
                    case "alter":
                        count = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteNonQuery(sql);
                        break;
                    case "select":
                        if ("bozhong" == con)
                        {
                            string message;
                            bool status = DbFactory.Init(AppInfo.con_bozhong).TestConnection(out message);
                            if (!status)
                            {
                                Response.Write(string.Format("{0},{1}", status, message));
                            }
                            dtList = DbFactory.Init(AppInfo.con_bozhong).ExecuteDataTable(sql);
                        }
                        else if ("wanghu" == con)
                        {
                            string message;
                            bool status = DbFactory.Init(AppInfo.con_wanghu).TestConnection(out message);
                            if (!status)
                            {
                                Response.Write(string.Format("{0},{1}", status, message));
                            }
                            dtList = DbFactory.Init(AppInfo.con_wanghu).ExecuteDataTable(sql);
                        }
                        else
                        {
                            dtList = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable(sql);
                        }
                        break;

                }
            }
        }
        Dictionary<string, string> GetSimpleQuerySqlstement()
        {
            Dictionary<string, string> simpleQuery = new Dictionary<string, string>();
            simpleQuery.Add("t_user", "select top {0} user_id, nickname, game_id_bozhong, game_id_wanghu, is_agent, agent_id, parent1_uid, parent2_uid, top_agent_id from t_user order by user_id desc");
            simpleQuery.Add("t_user_agent", "select top {0} a.agent_id, u.user_id, u.nickname, a.is_agent_time, u.parent1_uid, u.parent2_uid, u.top_agent_id from t_user u inner join t_user_agent a on u.user_id=a.user_id order by a.agent_id desc");
            simpleQuery.Add("t_finance_transaction_details", "select top {0} account_id, user_id, sponsor_uid, trade_type, amount, out_trade_no, game_mact_id, benefactor_game_id, benefactor_game_nickname, remark, create_time, transform_amount, transform_amount_type from t_finance_transaction_details");
            return simpleQuery;
        }
        protected void dologin()
        {
            string username = RequestUtil.FormString("username", maxLen: 16).Trim();
            string password = RequestUtil.FormString("password", maxLen: 16).Trim();
            if (username.Length < 1 || password.Length < 1)
            {
                Response.Redirect("DbView.aspx?action=login&result=invide_login", true);
            }
            if (!loginusers.ContainsKey(username))
            {
                Response.Redirect("DbView.aspx?action=login&result=user_not_found", true);
            }
            if (password != loginusers[username])
            {
                Response.Redirect("DbView.aspx?action=login&result=password_is_wrong", true);
            }
            Session["debuglogin"] = username;
            Response.Redirect("DbView.aspx?result=login_success", true);
        }
    }
}